<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>任务分派</title>

    {% include 'template/baseCss.volt' %}
    <link href="/css/vendor/page-control.css" rel="stylesheet" type="text/css">
    <link href="/css/vendor/dispatch-mission.less" rel="stylesheet/less" type="text/css">
    <script src="/js/less.min.js"></script>
</head>

<body>
<main>
    <!-- 地图显示块 -->
    <div class="map-wrap">
        <div id="map-container"></div>
        <div class="title-bar" id="map-task-title"></div>
    </div>

    <!-- 左侧的主菜单 -->
    <div class="main-menu">
        <ul id="main-menu-list" class="menu">
            <li class="button" selected>分派信息</li>
            <li class="button">工程信息</li>
        </ul>

        <div id="mission-info-wrap">
            <p class="proj-name-title">工程名称:</p>
            <p class="proj-name" id="project-name"></p>
            <p class="proj-change button" id="btn-change-project" onClick="dispatchMissionM.showProjectSelection();">
                更换</p>
            <div id="block-info">

            </div>
            <div id="operation-history" style="visibility: hidden">
                <p class="history-title">操作历史:</p>
                <table id="dispatch-list-history" class="history" cellpadding="0" cellspacing="0">

                </table>
            </div>
            {#<div class="area-title">备 注</div>#}
            {#<textarea class="comment-box" rows=6></textarea>#}
        </div>

        <ul class="bottom-bar">
            <li><p class="button" id="btn-save-dispatch" onclick="DispatchProxy.clickAddDispatch()">
                    分&nbsp;&nbsp;&nbsp;派</p></li>
        </ul>

        <div id="project-info-wrap" class="remove">

        </div>
    </div>


    <!-- 用于点击进入菜单之初，先用深色掩盖整个页面，选择工程后再将透明度减到0然后移除 -->
    <div id="page-dark-mask" style="display: none"></div>
    <!-- 工程选择列表 -->
    <div id="project-selection-page-mask" class="page-mask-container" style="visibility: hidden;">
        <div id="project-selection-wrap" class="selection-wrap center-vh">
            <h1>工程选择</h1>
            <table class="condition">
                <tr>
                    <td><label class="name">名称:</label><input name="project_name" type="text"></td>
                </tr>

            </table>
            <div class="filter-btn button" id="btn-search-project">筛 选</div>

            <div class="data-wrap">
                <div class="table-title-wrap">
                    <table id="table-header" class="title" cellpadding="0" cellspacing="0" border="0"
                           bordercolor="#d8d8d8">

                    </table>
                </div>
                <div class="table-data-wrap">
                    <table id="mytable" class="data" cellpadding="0" cellspacing="0" border="0" bordercolor="#d8d8d8">

                    </table>
                </div>
            </div>
        </div> <!-- #project-selection-wrap -->
    </div> <!-- #project-selection-page-mask -->

    <!-- 人员选择列表 -->
    <div id="user-selection-page-mask" class="page-mask-container" style="visibility:hidden;">
        <div id="user-selection-wrap" class="selection-wrap center-vh">
            <h1>人员选择</h1>
            <table class="condition">
                <tr>
                    <td><label class="name">姓名:</label><input name="real_name"  type="text"></td>
                    <td><label class="name">邮箱:</label><input name="email" class="e-date" type="text"></td>
                    <td><label class="name">手机号:</label><input name="phone" class="e-date" type="text"></td>
                </tr>
                <tr>
                    <td><label class="name">公司:</label><input name="company" type="text"></td>

                </tr>
            </table>
            <div class="filter-btn button" id="btn-search-user">筛 选</div>

            <div class="data-wrap">
                <div class="table-title-wrap">
                    <table id="user-table-header" class="title" cellpadding="0" cellspacing="0" border="0"
                           bordercolor="#d8d8d8">

                    </table>
                </div>
                <div class="table-data-wrap">
                    <table id="user-table-data" class="data" cellpadding="0" cellspacing="0" border="0"
                           bordercolor="#d8d8d8">

                    </table>
                </div>
            </div>
        </div> <!-- #user-selection-wrap -->
    </div> <!-- #user-selection-page-mask -->

    <div class="rows-perpage-wrap hidden">
        <select id="rows-perpage-select">
            <option value="15">15</option>
            <option value="25" selected>25</option>
            <option value="50">50</option>
            <option value="100">100</option>
            <option value="150">150</option>
            <option value="200">200</option>
        </select>
        <label>每页显示条数</label>
    </div>
</main>

<div style="display: none">

    <div id="projectWork">{{ projectWork }}</div>
    <div id="dispatchList">{{ dispatchList }}</div>
    <div id="projectInfo">{{ projectInfo }}</div>
    <div id="curUser">{{ curUser }}</div>
</div>


</body>

{% include 'template/baseJs.volt' %}
<script src="/js/vendor/page-control.js"></script>
<script src="/js/vendor/dispatch-mission.js"></script>
<script src="/js/vendor/data-loading.js"></script>
{% include 'template/baseMap.volt' %}{% include 'template/baseMapKey.volt' %}
<script type="text/javascript" src="/js/vendor/transform.js"></script>
<script type="text/javascript" src="/js/vendor/google-map-manager.js"></script>
<script>
    // 左侧菜单变化
    dispatchMissionM.mainMenuChangedToIndex = function (index) {
        console.log((index == 0) ? "切换到任务信息" : "切换到工程信息");
    };

    DispatchProxy = {
        curProjectId: false,
        curProjectData: false,//当前项目信息
        curTaskId: false,
        curDispatchDict: false,//当前分派,
        curIsSelectedUser: false,
        curWorkId: false,
        curUser: false,
        curlocationCS:"wgs84",
        init: function () {
            GoogleMapManager.initMapWithIdAndMapType("map-container");
            this.resetState();
            this.curUser = eval("(" + $("#curUser").text() + ")");
            this.curWorkId = getQueryString("work_id");
            if (this.curWorkId) {
                this.initDetailMode();
                $("#operation-history").css("visibility", "visible");
            } else {
                $("#page-dark-mask").css("display", "block");
                $("#project-selection-page-mask").css("visibility", "visible");
                this.bindProjectSearch();
            }

            //绑定回调
            dispatchMissionM.userSelectionCallBack = this.clickDispatchUser;
        },

        initDetailMode: function () {
            $("#btn-save-dispatch").text("更新分派")
            $("#btn-change-project").hide();
            //加载项目
            var data = eval("(" + $("#projectInfo").text() + ")");
            DispatchProxy.curProjectData = data;
            DispatchProxy.loadingProjectInfo();
            //把人员分派情况也加载进去
            var userList = eval("(" + $("#dispatchList").text() + ")");
            for (var i = 0; i < userList.length; i++) {
                var item = userList[i];
                DispatchProxy._UItaskSelect(item["task_local_id"], item["nickname"]);
            }
            DispatchProxy._UItaskHistory(userList);

        },
        //重置状态
        resetState: function () {
            this.curIsSelectedUser = false;
            this.curDispatchDict = new Object();
        },
        //点击添加了分派
        clickAddDispatch: function () {
            if (DispatchProxy.curIsSelectedUser) {
                var projectId = DispatchProxy.curProjectId;
                feimaPost("/task/addProjectWork", {
                    "project_id": projectId,
                    "task_list": DispatchProxy.curDispatchDict,
                    "project_work_id": DispatchProxy.curWorkId
                }, function (result) {

                    if (result.status == 0) {

                        var workId = result.data["project_work_id"];
                        if (DispatchProxy.curWorkId) {
                            FAlert("更新成功", function () {
                                window.location.reload();
                            });
                        } else {
                            FConfirm("您成功地分派了任务,ID:" + workId + ",请问您是否继续分派?", function (result) {
                                if (result) {
                                    window.location.reload();
                                } else {
                                    window.location.href = "/task/list";
                                }
                            });
                        }

                    }
                });
            } else {
                FAlert("请选择分派用户");
            }
        },
        clickProject: function (projectId) {
            DispatchProxy.curProjectId = projectId;
            //请求项目的详细信息
            feimaPost("/task/doProjectInfo", {
                "project_id": projectId
            }, function (result) {
                if (result.status == 0) {
                    DispatchProxy.resetState();
                    DispatchProxy.curProjectData = result.data;
                    DispatchProxy.loadingProjectInfo();
                    dispatchMissionM.clickProjectItemAction();
                } else {
                    FAlert(result.message);
                }
            });
        },
        //选择了用户
        clickUser: function (userid) {
            dispatchMissionM.clickUserItemAction();
            var user = DispatchProxy._getCurUserInfo(userid);
            if (user) {
                var nickName = user["nickname"];
                DispatchProxy._UItaskSelect(DispatchProxy.curTaskId, nickName);
                var data = DispatchProxy._getcurSuveyAndTaskInfo(DispatchProxy.curTaskId);
                var block = data["block"];
                var dispatchData = {
                    "project_local_id": block["project_id"],
                    "survey_local_id": block["id"],
                    "user_id": user["id"]
                };
                DispatchProxy.curDispatchDict[DispatchProxy.curTaskId] = dispatchData;
                DispatchProxy.curIsSelectedUser = true;
            }
        },
        //点击了任务
        clickTask: function (id) {
            //加载任务信息
            var dataInfo = this._getcurSuveyAndTaskInfo(id);
            var block = dataInfo["block"];
            var task = dataInfo["task"];
            var title = block["survey_area_name"] + "-" + task["flight_task_name"];
            $("#map-task-title").text(title);
            this._UIdrawBlock(block);
            this._UIDrawTaskWay(task, block['entry_direction']);
        },
        //点击了分派
        clickDispatchUser: function (id) {
            DispatchProxy.curTaskId = id;

            DispatchProxy.bindUserSearch();
        },
        //加载项目信息
        loadingProjectInfo: function () {
            //清空block的信息
            $("#block-info").html("");
            if (this.curProjectData) {

                $("#project-name").text(this.curProjectData["project_name"]);
                var htmlStr = "";
                var blockInfoStr = "";
                for (var i = 0; i < this.curProjectData["blocks"].length; i++) {
                    htmlStr += this._UIcreateBlockItemStr(this.curProjectData["blocks"][i]);
                    blockInfoStr += this._UIcreateBlockInfoStr(this.curProjectData["blocks"][i]);
                }


                $("#block-info").html(htmlStr);

                $("#project-info-wrap").html(blockInfoStr);
            }

        },
        //绑定项目搜索
        bindProjectSearch: function () {
            PageDataProxy.init({
                "drone_fileter_id": "project-selection-wrap",
                "btn_search_data_id": "btn-search-project",
                "url": "/task/doListMyProject",
                "table_id": "#mytable",
                "page_control_id": "#project-selection-wrap",
                "page_size_id": "#rows-perpage-select",
                "page_total_id": "#data_count_total",
                "use_check_box": false,
                "data_field_process": function (name, value) {
                    if (name == "company") {
                        return PageDataProxy.formatShortContent(value, 18);
                    }
                    if (name == 'id') {

                        value = "<a href='javascript:void(0)' onclick=DispatchProxy.clickProject('" + value + "')>" + value + "</a>";
                    }
                    return value;
                },
                "table_style": {

                    "id": "width-s",
                    "project_name": "width-200",
                    "created_at": "width-m",
                    "updated_at": "width-m"
                }


            });
        },
        //绑定项目搜索
        bindUserSearch: function () {
            PageDataProxy.init({

                "drone_fileter_id": "user-selection-wrap",
                "btn_search_data_id": "btn-search-user",
                "url": "/task/doListMyUsers",
                "table_id": "#user-table-data",
                "table_header_id": "#user-table-header",
                "page_control_id": "#user-selection-wrap",
                "page_size_id": "#rows-perpage-select",
                "page_total_id": "#data_count_total",
                "use_check_box": false,
                "data_field_process": function (name, value) {
                    if (name == "company") {
                        return PageDataProxy.formatShortContent(value, 18);
                    }
                    if (name == 'id') {

                        value = "<a href='javascript:void(0)' onclick=DispatchProxy.clickUser('" + value + "')>" + value + "</a>";
                    }
                    return value;
                },
                "table_style": {
                    "id": "width-s",
                    "project_name": "width-200",
                    "created_at": "width-m",
                    "updated_at": "width-m"
                }


            });
        },
        _UItaskHistory: function (dataArray) {

            var str = "<tr><td class='receiver'>接收人</td><td class='dispatcher'>任务</td><td class='mission'>状态</td><td class='time'>时间</td><td class='comment'>消息</td></tr>";
            for (var i = 0; i < dataArray.length; i++) {
                var data = dataArray[i];
                str += "<tr><td class='receiver'>" + data["nickname"] + "</td>";
                var taskData = DispatchProxy._getcurSuveyAndTaskInfo(data["task_local_id"]);
                var taskName = taskData["task"]["flight_task_name"];
                str += "<td class='dispatcher'>" + taskName + "</td>";
                var statusStr = "待处理";
                var status = data["status"];
                var statusStr = getStatusInfo(status).title;
                var taskId = data["id"];
                var created_at = data["created_at"];
                str += "<td class='mission'>" + statusStr + "</td>";
                str += "<td class='time'>" + data["created_at"] + "</td>";

                var funcStr = "clickShowMessageWindow(" + i + ")";
                str += "<td class='comment button' unread onclick=" + funcStr + "></td>";
            }
            $("#dispatch-list-history").html(str);
        },
        //更新分派用户UI
        _UItaskSelect: function (taskId, nickName) {
            var selector = "[task-id=" + taskId + "]";
            $(selector).children("img").removeClass("hidden").next().text("重新分派")
                    .parent().prev().text(nickName);
        },
        //创建block信息
        _UIcreateBlockItemStr: function (blockItem) {
            var surveyName = blockItem["survey_area_name"];
            if(blockItem["plane_type"]){

                var planeTypeFirstChar=blockItem["plane_type"].substr(0,1);

                if(blockItem["plane_type"]=="D1000"
                    ||
                        planeTypeFirstChar=="P"
                ){
                    DispatchProxy.locationCS="gcj02";
                }else{
                    DispatchProxy.locationCS="wgs84";
                }
            }else{
                DispatchProxy.locationCS="wgs84";
            }
            var htmlStr = "";
            htmlStr += "<div class='area-title'>" + surveyName + "</div>";
            htmlStr += "<table class='mission' cellpadding='0' cellspacing='0'>";
            var tasks = blockItem["tasks"];
            if (tasks) {

                for (var i = 0; i < tasks.length; i++) {
                    var taskItem = tasks[i];
                    var taskName = taskItem["flight_task_name"];
                    var taskId = taskItem['id'];
                    htmlStr += "<tr onclick=DispatchProxy.clickTask('" + taskId + "')>"
                            + "<td class='name'>" + taskName + "</td>"
                            + "<td class='user'></td>"
                            + "<td class='action button' task-id='" + taskId + "' onClick='dispatchMissionM.showUserSelection(event,this);'>" +
                            "<img src='/images/dispatch-mission-retry.png' class='hidden'><span>分派</span></td></tr>";
                }

            }
            htmlStr += "</table>";
            return htmlStr;
        },
        _UIcreateBlockInfoStr: function (blockItem) {
            var blockStr = "<h1>" + blockItem["survey_area_name"] + "</h1>";
            blockStr += '<table cellpadding="0" cellspacing="0">';
            blockStr += '<tr>';
            blockStr += '<td class="name">飞机型号</td>';
            blockStr += '<td class="value">' + blockItem["plane_type"] + '</td>';
            blockStr += '<td class="name">相机类型</td>';
            blockStr += '<td class="value">' + blockItem["camera_type"] + '</td>';
            blockStr += '</tr>';
            blockStr += '<tr>';
            blockStr += '<td class="name">最高GSD</td>';
            blockStr += '<td class="value">' + blockItem["high_gsd"] + '</td>';
            blockStr += '<td class="name">最低GSD</td>';
            blockStr += '<td class="value">' + blockItem["low_gsd"] + '</td>';
            blockStr += '</tr>';
            blockStr += '</table>';
            var location=FeimaCSSystem.googleMapCS({
                lat:blockItem["home_lat"],
                lng:blockItem["home_lng"],
                cs:DispatchProxy.locationCS
            });
            if(location.lat!=0&&
                            location.lng!=0
            ){
                GoogleMapManager.setCenter(location);
            }
            return blockStr;
        },
        //绘制测区
        _UIdrawBlock: function (block) {
            if (block) {
                GoogleMapManager.setZoom(13);
                var polyData =GoogleMapManager.string2PolyData({
                    "string":block["survey_area_coordinate_points"],
                    "cs":DispatchProxy.locationCS
                });
                var location=FeimaCSSystem.googleMapCS({
                    "lat":block["home_lat"],
                    "lng":block["home_lng"],
                    "cs":DispatchProxy.locationCS
                });
                GoogleMapManager.drawPolygon(polyData);
                if(location.lat!=0&&
                        location.lng!=0
                ){

                    GoogleMapManager.setCenter(location);
                }

            }

        },
        //绘制航线
        _UIDrawTaskWay: function (task, direction) {
            if (task) {
                var polylineDataStr = task["task_coordinate_waypoints"];
                var polylineDataArray = polylineDataStr.split("FF");
                if(polylineDataArray.length>=2){
                    var entryDirection = parseInt(direction)
                    if (entryDirection == 2
                            || entryDirection == 4
                    ) {
                        polylineDataStr = polylineDataArray[1];
                    } else {
                        polylineDataStr = polylineDataArray[0];
                    }
                }

                var polyData =GoogleMapManager.string2PolyData({
                    "string":polylineDataStr,
                    "cs":DispatchProxy.locationCS
                });
                GoogleMapManager.drawPolyLines(polyData);
            }
        },

        //获取用户信息
        _getCurUserInfo: function (userId) {
            var data = PageDataProxy.currentData["data"];
            for (var i = 0; data.length; i++) {
                var user = data[i];
                if (userId == user["id"]) {
                    return user;
                }
            }
            return null;
        },
        //通过任务ID获取survey和task信息
        _getcurSuveyAndTaskInfo: function (id) {
            if (this.curProjectData) {
                var blocks = this.curProjectData["blocks"];
                for (var i = 0; i < blocks.length; i++) {
                    var blockItem = blocks[i];

                    for (var j = 0; j < blockItem["tasks"].length; j++) {
                        var task = blockItem["tasks"][j];
                        if (task["id"] == id) {
                            return {
                                "block": blocks[i],
                                "task": task
                            };
                        }
                    }
                }
            }
            return null;
        }
    };

    $(function () {


        DispatchProxy.init();
    });
    function getStatusInfo(statusId) {
        if (statusId == 2) {
            return {
                title: "已接收",
                color: "#3CD814"
            }
        }
        if (statusId == 3) {
            return {
                title: "已拒绝",
                color: "#FC4E4E"
            }
        }
        if (statusId == 0) {
            return {
                title: "待处理",
                color: "#FFF700"
            }
        }


    }
    var curAssignId = 0;

    function clickShowMessageWindow(index) {
        loadingView.show();
        var userList = eval("(" + $("#dispatchList").text() + ")");
        var data = userList[index];
        var taskData = DispatchProxy._getcurSuveyAndTaskInfo(data["task_local_id"]);
        var taskName = taskData["task"]["flight_task_name"];
        var status = data["status"];
        var taskId = data["id"];
        var created_at = data["created_at"];
        var statusInfo = getStatusInfo(status);
        curAssignId = taskId;
        // 备注聊天信息
        var commentData = {
            missionName: taskName,
            dispatchTime: created_at,
            stateColor: statusInfo.color,
            stateName: statusInfo.title,

        };
        commentChatM.show(commentData, function (toSendData) {
            commentChatM.sendBtnEnable(false);
            console.log(toSendData);
            feimaPost("/task/reply", {
                "id": curAssignId,
                "message": toSendData
            }, function (result) {
                commentChatM.sendBtnEnable(true);
                if (result.status == 0) {
                    var date = new Date();
                    commentChatM.clearInput();

                    commentChatM.appendMsgs([{
                        time: date.Format("yyyy-MM-dd hh-mm"),
                        icon: DispatchProxy.curUser.iconUrl ? DispatchProxy.curUser.iconUrl : "/images/main/main_user_icon.png",
                        name: DispatchProxy.curUser.name,
                        content: toSendData,
                        isLeft: false,
                    }]);
                }
            });
        });

        feimaPost("/task/replyList", {
            "id": taskId
        }, function (result) {
            loadingView.remove();
            if (result.status == 0) {

                if (result.data) {
                    var array = new Array();
                    for (var i = 0; i < result.data.length; i++) {
                        var item = result.data[i];
                        var isLeft = true;
                        if (item["user_id"] == DispatchProxy.curUser["userId"]) {
                            isLeft = false;
                        }
                        array.push(
                                {
                                    "time": item["created_at"],
                                    "icon": item["icon_url"] ? item["icon_url"] : "/images/main/main_user_icon.png",
                                    "content": item["info"],
                                    "isLeft": isLeft,
                                    "name": item["nickname"]
                                }
                        )
                    }
                    commentChatM.appendMsgs(array);
                }

            }
        });
    }


</script>

</html>






